#region Copyright Jonathan Quiros

//	
// All rights are reserved. Reproduction or transmission in whole or in 
// part, in any form or by any means, electronic, mechanical or otherwise, 
// is prohibited without the prior written consent of the copyright owner.
//
// Filename: IncludeExtension.cs
//

#endregion

using System;
using System.Data.Objects;
using System.Linq.Expressions;

namespace Novagoal.Repositories.Extensions
{
    public static class IncludeExtension
    {
        #region CONSTANTS



        #endregion

        #region PROPERTIES

        

        #endregion

        #region PUBLIC METHODS

        public static ObjectQuery<T> Include<T>(this ObjectQuery<T> query, Expression<Func<T, object>> includes)
            where T : class
        {
            return query.Include(GetExpressionName(includes.Body as MemberExpression));
        }

        private static string GetExpressionName(MemberExpression memberExpression)
        {
            if (memberExpression.Expression.NodeType == ExpressionType.Parameter)
            {
                return memberExpression.Member.Name;
            }

            if (memberExpression.Expression.NodeType == ExpressionType.MemberAccess)
            {
                return string.Format("{0}.{1}",
                                     GetExpressionName(memberExpression.Expression as MemberExpression),
                                     memberExpression.Member.Name);
            }

            var methodCallExpression = (MethodCallExpression)memberExpression.Expression;

            if (methodCallExpression.Arguments.Count != 1)
            {
                throw new Exception("invalid method call in Include expression");
            }

            return string.Format("{0}.{1}",
                                 GetExpressionName(methodCallExpression.Arguments[0] as MemberExpression),
                                 memberExpression.Member.Name);
        }

        #endregion

        #region PRIVATE METHODS



        #endregion
    }
}